﻿namespace ScrumLite.Data
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using ScrumLite.Data;

    public class RoleStore : IRoleStore
    {
        public Role GetRole(Guid roleId)
        {
            using (ScrumLiteDataContext ctx = new ScrumLiteDataContext())
            {
                var role = ctx.Roles.SingleOrDefault(r => r.id == roleId);

                return role;
            }
        }
        
        public Role[] GetProjectRoles(Guid projectId)
        {
            using (ScrumLiteDataContext ctx = new ScrumLiteDataContext())
            {
                var roles = (from pr in ctx.ProjectRoles
                             where pr.fk_project == projectId
                             select pr.Role).ToArray();

                return roles;
            }
        }

        public Ability[] GetRoleAbilities(Guid projectId, Guid roleId)
        {
            using (ScrumLiteDataContext ctx = new ScrumLiteDataContext())
            {
                var abilities = (from pr in ctx.ProjectRoles
                                 from ra in pr.Role.RoleAbilities
                                 where pr.fk_role == roleId && pr.fk_project == projectId
                                 select ra.Ability).ToArray();

                return abilities;
            }
        }

        public void AddRoleToProject(Guid projectId, string roleName, string [] abilityIds)
        {
            using (ScrumLiteDataContext ctx = new ScrumLiteDataContext())
            {
                Role role = new Role() { id = Guid.NewGuid(), name = roleName };
                ctx.Roles.InsertOnSubmit(role);
                ProjectRole projectRole = new ProjectRole() { id = Guid.NewGuid(), fk_project = projectId, fk_role = role.id };
                ctx.ProjectRoles.InsertOnSubmit(projectRole);

                if (abilityIds!=null)
                    foreach (string abilityId in abilityIds)
                    {
                        RoleAbility roleAbility = new RoleAbility() { id = Guid.NewGuid(), fk_ability = new Guid(abilityId), fk_role = role.id };
                        ctx.RoleAbilities.InsertOnSubmit(roleAbility);
                    }

                ctx.SubmitChanges();
            }
        }
    }
}
